<template>
  <div class="goods page">
    <div class="wrapper" ref="webview">
      <van-sticky v-if="isNavFixed">
        <van-nav-bar class="bg_white" :title="goodsInfo.goods_name" left-arrow @click-left="$router.go(-1)" />
      </van-sticky>
      <div class="swipe">
        <div class="van-icon van-icon-arrow-left van-nav-bar__arrow" v-if="!isNavFixed" @click="$router.go(-1)"></div>
        <div class="video_popup-close van-icon van-icon-cross" v-if="isVideoPopup" @click="VideoPopupClose"></div>
        <van-swipe :autoplay="3000" class="home-swipe" @change="onChange">
          <van-swipe-item v-for="(item, index) in imageList" :key="index">
            <div class="img">
              <van-image width="100%" :height="clientWidth" fit="contain" lazy-load :src="item">
                <template v-slot:loading>
                  <van-loading type="spinner" size="24" />
                </template>
              </van-image>
            </div>
          </van-swipe-item>
          <div class="custom-indicator" slot="indicator">
            {{ current + 1 }}/{{imageList.length}}
          </div>
        </van-swipe>
        <div class="video_time" v-if="goodsInfo.video_duration">
          <span class="time" @click="openVideo">{{goodsInfo.video_duration | MillisecondToDate}}</span>
        </div>
        <div class="video_popup" :class="{active:isVideoPopup}">
          <div id="Player"></div>
        </div>
      </div>
      <div class="goods-info">
        <div class="g-price-inventory">
          <span class="g-price m-price">{{goodsInfo.shop_price}}</span>
          <!-- <span class="g-inventory">库存{{goodsInfo.total_stock}}</span> -->
          <div class="g-share-collection">
            <!-- <span class="icon-share">分享</span> -->
            <span class="icon-collection" :class="{active: isFavorite}" @click="goodsFavorite">{{!isFavorite?'收藏':'取消收藏'}}</span>
          </div>
        </div>
        <div class="g-title">{{goodsInfo.goods_name}}</div>
        <div class="g-describe">{{goodsInfo.goods_tips}}</div>
      </div>
      <div class="goods-item_floor goods-coupon" @click="isPopupCoupon=true">
        <div class="g-left">
          <span class="name">领劵</span>
        </div>
        <div class="goods-item_floor_content goods-pd">
          <template v-for="(item,index) in couponList">
            <span class="g-coupon" v-if="index<3" :key="index">{{item.coupon_name}}</span>
          </template>
        </div>
        <div class="g-more">
          <span class="dot"></span>
          <span class="dot r"></span>
          <span class="dot"></span>
        </div>
      </div>
      <div class="goods-parameter">
        <div class="goods-item_floor goods-specifications" @click="isPopup=true">
          <div class="g-left">
            <span class="name">已选</span>
          </div>
          <div class="goods-item_floor_content">{{skuInfo.names}}</div>
          <div class="g-more">
            <span class="dot"></span>
            <span class="dot r"></span>
            <span class="dot"></span>
          </div>
        </div>
        <div class="goods-item_floor" v-if="freightTempName">
          <div class="g-left">
            <span class="name">运费</span>
          </div>
          <div class="goods-item_floor_content">{{freightTempName}}</div>
        </div>
        <div class="goods-item_floor bd_none" v-if="attrList.length>0" @click="isPopupParameter=true">
          <div class="g-left">
            <span class="name">参数</span>
          </div>
          <div class="goods-item_floor_content"></div>
          <div class="g-arrow-right"></div>
        </div>
      </div>
      <div class="goods-comments">
        <div class="goods-c-title">
          <div class="g-l">
            <span class="title">点评</span>
            <span class="num">{{goodsInfo.appraise_num}}条评价</span>
          </div>
          <div class="g-r" @click="$router.push({'path':'/comments/all', query: {gid: gid}})">
            <span class="percentage">好评{{goodsInfo.good_appraise_ratio}}%</span>
          </div>
        </div>
        <div class="content">
          <comments :list="commentsList">
            <div class="nodata">暂无数据</div>
          </comments>
          <div class="all-comments-list" @click="$router.push({'path':'/comments/all', query: {gid: gid}})">查看全部评价</div>
        </div>
      </div>
      <div class="goods-store">
        <div class="info">
          <div class="goods-store-img">
            <img :src="shopInfo.shop_img" />
          </div>
          <div class="goods-store-info" @click="$router.push({'path':'/store', query: {id: shopInfo.id}})">
            <div class="name">{{shopInfo.shop_name}}</div>
            <div class="s-info">
              <span class="fans">粉丝人数{{shopInfo.favorites_num}}万</span>
              <span class="">全部商品 {{shopInfo.goods_num}}</span>
            </div>
          </div>
          <div class="g-arrow-right"></div>
        </div>
        <div class="btn">
          <span class="icon-collection-store" @click="storeFavorite">收藏店铺</span>
          <span class="icon-go-store" @click="$router.push({'path':'/store',query: {id: shopInfo.id}})">进入店铺</span>
        </div>
      </div>
      <div class="goods-content">
        <div class="title van-hairline-j--bottom">
          <span>商品详情</span>
        </div>
        <div class="content" v-html="goodsInfo.goods_desc">
        </div>
      </div>
    </div>
    <div class="goods-action van-hairline-j--top">
      <div class="goods-action-icon">
        <div class="action-icon" @click="$router.push({'path':'/store', query: {id: shopInfo.id}})">
          <i class="action-icon-store"></i>
          <span class="name">店铺</span>
        </div>
        <div class="action-icon" @click="$router.push({'path':'/cart', query: {id: shopInfo.id}})">
          <i class="action-icon-cart"></i>
          <span class="name">购物车</span>
          <span class="badge" v-if="cartNum > 0">{{cartNum}}</span>
        </div>
      </div>
      <van-button color="#FF9B1B" class="btn" @click="isPopup=true,cartMods='1'">加入购物车</van-button>
      <van-button color="#FF0034" class="btn" @click="isPopup=true,cartMods='2'">立即购买</van-button>
    </div>
    <!--优惠劵-->
    <van-popup v-model="isPopupCoupon" round position="bottom">
      <div class="g-popup-coupon">
        <template v-for="(item,index) in couponList">
          <coupon-list :state="1" :key="index" :item="item" @success="collectSuccess" />
        </template>
      </div>
    </van-popup>
    <!--商品参数-->
    <van-popup v-model="isPopupParameter" round position="bottom">
      <div class="g-parameter">
        <span class="van-icon van-icon-cross" @click="isPopupParameter=false"></span>
        <template v-for="(item,index) in attrList">
          <div class="rows" :key="index">
            <div class="label">{{item.attr_name}}：</div>
            <div class="info">{{item.attr_val}}</div>
          </div>
        </template>
      </div>
    </van-popup>
    <!--SKU库存-->
    <van-popup v-model="isPopup" round position="bottom" style="overflow-y: unset;">
      <div class="g-sku-container">
        <div class="g-sku-header">
          <div class="g-sku-header__img-wrap">
            <van-image width="100%" :height="$tools.toPX(200)" fit="contain" lazy-load :src="goodsInfo.goods_img">
              <template v-slot:loading>
                <van-loading type="spinner" size="24" />
              </template>
            </van-image>
          </div>
          <div class="g-sku-header__goods-info">
            <div class="g-sku__goods-price">
              <span class="m-price">{{firstNormPrice || goodsInfo.shop_price}}</span>
            </div>
            <div class="g-sku__goods-item">
              <span class="label">已选：</span>
              <div class="info">{{skuInfo.names}}</div>
            </div>
          </div>
          <span class="van-icon van-icon-cross" @click="isPopup=false"></span>
        </div>
        <div class="g-sku-body">
          <template v-for="(_item,key) in specList">
            <div class="g-sku-body__item" :key="key">
              <div class="g-sku-body__item-title">{{_item.spec_name}}</div>
              <sku-radio-group v-model="skuInfo" @change="changeFirstNormName">
                <template v-for="(item,index) in _item.sub">
                  <sku-radio :label="item.item_name" :pid="_item.id" :key="index" :index="key" :value="item">
                  </sku-radio>
                </template>
              </sku-radio-group>
            </div>
          </template>
          <div class="g-sku-body__item">
            <div class="g-sku-body__item-title">数量</div>
            <div class="g-sku-body__inventory">
              <van-stepper v-model="buyNumber" input-width="50" :disabled="!stock" min="1" :max="stock" />
              <span class="info">剩余{{!stock?0:stock-buyNumber}}件商品</span>
            </div>
          </div>
        </div>
      </div>
      <div class="g-sku-actions">
        <van-button color="#FF0034" :disabled="!stock" round :loading="buyLoading" class="btn" @click="exchange">{{cartMods === '1'?'确定购买':'立即购买'}}</van-button>
      </div>
    </van-popup>
  </div>
</template>
<script>
// import Xgplayer from 'xgplayer-vue';
import XPlayer from 'xgplayer';
export default {
  name: 'goods',
  data () {
    return {
      clientWidth: document.body.clientWidth,
      isPopup: false,
      buyLoading: false,
      cartMods: '2', // 购物方式
      isPopupParameter: false,
      isPopupCoupon: false,
      firstNormName: '',
      skuInfo: {},
      firstNormPrice: '',
      stock: 0,
      gid: 0, // 当前产品ID
      buyNumber: 1,
      current: 0,
      isNavFixed: false,
      skuText: [],
      goodsInfo: {}, // 商品信息
      shopInfo: {}, // 店铺信息
      normList: [],
      imageList: [], // 商品轮播图
      goodsSpecList: [], // 所有规格列表参数
      isVideoPopup: false,
      freightTempName: '', // 运费模板
      Player: null,
      cartNum: 0, // 购物车数量
      specList: [], // 商品规格
      attrList: [], // 属性列表
      couponList: [], // 优惠劵列表
      isFavorite: false, // 判断是否收藏成功
      isStoreFavorite: false, // 判断收藏店铺
      commentsList: [],
      config: {
        fluid: true,
        // autoplay: true,
        preloadTime: 15, // 默认预加载 15 秒
        playsinline: true,
        videoInit: true,
        // 'x5-video-player-type': 'h5',
        'x5-playsinline': '',
        'webkit-playsinline': 'true',
        'x-webkit-airplay': 'true',
        'x5-video-player-type': 'h5',
        'x5-video-player-fullscreen': '',
        'x5-video-orientation': 'portraint',
        width: document.body.clientWidth,
        height: document.body.clientWidth
        // ignores: ['fullscreen']
      }
    };
  },
  destroyed () {
    this.Player = null;
  },
  mounted () {
    this.$nextTick(() => {
      // 监听滚动条
      this.$BUS.$on('scroll', (data) => {
        this.isNavFixed = data > 50;
      });
    });
  },
  created () {
    this.getGoodsInfo();
  },
  methods: {
    VideoPopupClose () {
      this.isVideoPopup = false;
      this.Player.pause();
    },
    getGoodsInfo () {
      this.$toast.loading({ duration: 0 });
      this.$API.goods.goodsInfo({ sn: this.$route.query.sn }).then(res => {
        // console.log(res);
        if (!res.code) {
          if (!res.data.goods) {
            this.$dialog.alert({
              message: '当前商品已下架'
            }).then(() => {
              this.$router.go(-1);
              this.$toast.clear();
            });
          }
          this.gid = res.data.goods.id; // 商品Id
          this.skuInfo = {
            ids: res.data.selectedSpecIds, // 已选规格IDS
            names: res.data.selectedSpecItem// 已选规格
          };
          this.firstNormPrice = res.data.firstNormPrice;
          this.isFavorite = !!res.data.isFavorites;
          this.stock = res.data.selectedSpecStock; // 默认规格库存
          this.goodsInfo = res.data.goods;// 商品信息
          this.shopInfo = res.data.shop; // 店铺信息
          this.cartNum = res.data.cartNum; // 购物车数量
          this.getGoodsSpec(this.gid); // 获取商品规格
          this.getGoodsCoupon(this.gid);// 获取商品规格
          this.getGoodsAttr(this.gid);// 获取商品规格
          this.getComments(this.gid); // 获取评价
          this.goodsfreight(this.gid); // 获取评价
          // 产品视频
          if (res.data.goods.video_path) {
            this.Player = new XPlayer({
              id: 'Player',
              url: res.data.goods.video_path,
              ...this.config
            });
          }
          this.imageList = res.data.goods && res.data.goods.gallery.split(','); // 产品轮播图
        }
        this.$toast.clear();
      });
    },
    goodsfreight (id) {
      this.$API.goods.goodsfreight({ gid: id }).then(res => {
        if (!res.code) {
          this.freightTempName = res.data.tempName;
        } else {
          this.$toast('获取失败');
        }
      });
    },
    // 收藏店铺
    storeFavorite () {
      this.$toast.loading({ duration: 0 });
      this.$API.store.storeFavorite({ id: this.shopInfo.id }, 'add').then(res => {
        if (!res.code) {
          this.$toast('收藏成功');
        }
      });
    },
    // 获取商品规格
    getGoodsSpec (id) {
      this.$API.goods.goodsSpec({ gid: id }).then(res => {
        if (!res.code) {
          this.specList = res.data.specCatsList;
          this.goodsSpecList = res.data.goodsSpecList;
          this.changeFirstNormName(); // 规格默认值
        }
      });
    },
    // 获取评价列表
    getComments (id) {
      this.$API.goods.goodsAppraise({ gid: id, page: 1, limit: 3 }).then(res => {
        if (!res.code) {
          this.commentsList = res.data.map(item => {
            item.ImgList = [];
            item.ImgList = item.images.split(',');
            return item;
          });
        }
      });
    },
    // 获取商品属性
    getGoodsCoupon (id) {
      this.$API.goods.goodsCoupon({ gid: id }).then(res => {
        if (!res.code) {
          this.couponList = res.data; // 商品优惠劵
        }
      });
    },
    // 获取商品优惠劵
    getGoodsAttr (id) {
      this.$API.goods.goodsAttr({ gid: id }).then(res => {
        if (!res.code) {
          this.attrList = res.data; // 商品属性
        }
      });
    },
    // 领取优惠劵成功
    collectSuccess () {
      this.getGoodsAttr(this.gid); // 重新获取
    },
    // 获取购物车数量
    getcartList () {
      this.$API.cart.list().then(res => {
        if (!res.code) {
          this.cartNum = res.data.shopList.length;
        }
      });
    },
    // 商品收藏
    goodsFavorite (id) {
      if (!localStorage.getItem('Token')) {
        this.$store.dispatch('setLogin', true);
        return;
      }
      this.$toast.loading({ duration: 0 });
      this.$API.goods.goodsFavorite({ id: this.goodsInfo.id }, !this.isFavorite ? 'add' : 'cancel').then(res => {
        if (!res.code) {
          this.isFavorite = !this.isFavorite; // 商品收藏
          this.$toast(this.isFavorite ? '收藏成功' : '取消收藏');
        }
      });
    },
    // 打开视频
    openVideo () {
      this.isVideoPopup = true;
      this.Player.play();
    },
    onChange (index) {
      this.current = index;
    },
    // 选择规格
    changeFirstNormName () {
      console.log(this.skuInfo.ids);
      var chlidren = this.goodsSpecList.find(item => item.spec_ids === this.skuInfo.ids);
      this.firstNormPrice = chlidren && chlidren.spec_price;
      this.stock = chlidren && chlidren.spec_stock;
      this.normId = chlidren && chlidren.id; // 当前规格ID
    },
    // 加入购物车
    cartAdd (data) {
      if (!localStorage.getItem('Token')) {
        this.$store.dispatch('setLogin', true);
        return;
      }
      this.buyLoading = true;
      this.$API.cart.add(data).then(res => {
        if (!res.code) {
          this.$toast('成功加入购物车!');
          this.buyLoading = false;
          this.isPopup = false;
          this.cartNum += 1;
        }
      });
    },
    exchange () {
      if (!localStorage.getItem('Token')) {
        this.$store.dispatch('setLogin', true);
        return;
      }
      if (!this.normId) {
        this.$toast('必须选择一个规格');
        return;
      }
      var data = { sid: this.normId, num: this.buyNumber };
      // 判断是否是加入购物车
      if (this.cartMods === '1') {
        this.cartAdd(data);
      } else {
        this.$router.push({ 'path': '/order/confirm', query: data });
      }
    }
  }
};
</script>
<style lang="less" scoped>
@import '../../assets/style/goods.less';
</style>
